<template>
  <div class="video-player-container">
    <!-- 视频播放器容器 -->
    <div class="video-wrapper">
      <video ref="videoPlayer" class="video-player" :src="videoSource" :poster="poster" controls
        @timeupdate="handleTimeUpdate" @loadedmetadata="handleLoadedMetadata" @error="handleVideoError"></video>
    </div>

    <!-- 基础信息栏 -->
    <div class="basic-info-bar">
      <div class="info-item">
        <span class="info-label">当前位置:</span>
        <span class="info-value">{{ currentTimeFormatted }}s</span>
      </div>
      <div class="info-item">
        <span class="info-label">总时长:</span>
        <span class="info-value">{{ durationFormatted }}s</span>
      </div>
    </div>

    <!-- 控制按钮区域 -->
    <div class="control-panel">
      <div class="button-group primary-actions">
        <el-button type="primary" size="small" @click="setStartTime" :icon="Position" class="control-btn">
          设置起点
        </el-button>
        <el-button type="primary" size="small" @click="setEndTime" :icon="Position" class="control-btn">
          设置终点
        </el-button>
      </div>

      <div class="button-group time-adjust">
        <el-button size="small" @click="stepBackward" :icon="ArrowLeft" class="control-btn">
          -0.02s
        </el-button>
        <el-button size="small" @click="stepForward" :icon="ArrowRight" class="control-btn">
          +0.02s
        </el-button>
      </div>

      <div class="button-group markers">
        <el-button type="success" size="small" @click="addMarker1" :icon="Flag" class="control-btn">
          标记点1
        </el-button>
        <el-button type="success" size="small" @click="addMarker2" :icon="Flag" class="control-btn">
          标记点2
        </el-button>
        <!-- 新增清除标记点按钮 -->
        <el-button type="danger" size="small" @click="clearMarker1" :icon="Delete" class="control-btn"
          :disabled="marker1 < 0">
          清除标记1
        </el-button>
        <el-button type="danger" size="small" @click="clearMarker2" :icon="Delete" class="control-btn"
          :disabled="marker2 < 0">
          清除标记2
        </el-button>
      </div>

      <div class="button-group actions">
        <el-button type="warning" size="small" @click="addAttackAtMarker1" :icon="CirclePlus" class="control-btn">
          标记1添加Attack
        </el-button>
        <el-button type="info" size="small" @click="showInfoDialog = true" :icon="InfoFilled" class="control-btn">
          时间信息
        </el-button>
        <!-- 新增退出按钮 -->
        <el-button type="danger" size="small" @click="exitPlayer" :icon="Delete" class="control-btn">
          退出
        </el-button>
      </div>
    </div>

    <!-- 标记点显示区域 -->
    <div class="markers-display" v-if="startTime >= 0 || endTime >= 0 || marker1 >= 0 || marker2 >= 0">
      <el-tag v-if="startTime >= 0" type="primary" effect="light" class="marker-tag" @click="jumpToTime(startTime)">
        起点: {{ startTimeFormatted }}s
      </el-tag>
      <el-tag v-if="endTime >= 0" type="primary" effect="light" class="marker-tag" @click="jumpToTime(endTime)">
        终点: {{ endTimeFormatted }}s
      </el-tag>
      <el-tag v-if="marker1 >= 0" type="success" effect="light" class="marker-tag" @click="jumpToTime(marker1)">
        标记1: {{ marker1Formatted }}s
      </el-tag>
      <el-tag v-if="marker2 >= 0" type="success" effect="light" class="marker-tag" @click="jumpToTime(marker2)">
        标记2: {{ marker2Formatted }}s
      </el-tag>
    </div>

    <!-- 时间信息弹窗 -->
    <el-dialog title="时间信息详情" v-model="showInfoDialog" width="400px" :close-on-click-modal="false"
      :destroy-on-close="true">
      <el-scrollbar style="height: 300px;">
        <div class="dialog-content">
          <div class="info-row">
            <span class="dialog-label">起始时间:</span>
            <span class="dialog-value">{{ startTimeFormatted === '' ? '未设置' : startTimeFormatted +'s'}}</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">终点时间:</span>
            <span class="dialog-value">{{ endTimeFormatted ==='' ? '未设置' : endTimeFormatted +'s'}}</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">起始到终点时长:</span>
            <span class="dialog-value">{{ timeSpanFormatted }}s</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">标记1相对起点:</span>
            <span class="dialog-value">{{ marker1RelativeToStartFormatted }}s</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">标记点1:</span>
            <span class="dialog-value">{{ marker1Formatted === '' ? '未设置' : marker1Formatted+'s'}}</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">标记点2:</span>
            <span class="dialog-value">{{ marker2Formatted === '' ? '未设置' : marker2Formatted+'s'}}</span>
          </div>
          <div class="info-row">
            <span class="dialog-label">标记点间距:</span>
            <span class="dialog-value">{{ markersDistanceFormatted }}s</span>
          </div>
          <span class="dialog-label">若标记点1小于标记点2，标记点间距将被计算为0</span>
        </div>
      </el-scrollbar>
      <template #footer>
        <el-button @click="showInfoDialog = false">关闭</el-button>
      </template>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Position, ArrowRight, ArrowLeft, Flag, CirclePlus, InfoFilled, Delete } from '@element-plus/icons-vue';
import { ElButton, ElTag, ElDialog, ElMessage } from 'element-plus';

// 定义组件属性
defineProps({
  videoSource: {
    type: String,
    default: 'https://storage.googleapis.com/web-dev-assets/video-and-source-tags/chrome.mp4'
  },
  poster: {
    type: String,
    default: ''
  }
});

// 定义组件抛出事件
const emit = defineEmits(['add-attack', 'exit']);

// 视频元素引用
const videoPlayer = ref<HTMLVideoElement | null>(null);

// 状态管理
const currentTime = ref(0);       // 当前播放时间(秒)
const duration = ref(0);          // 视频总时长(秒)
const startTime = ref(-1);         // 起点时间
const endTime = ref(-1);           // 终点时间
const marker1 = ref(-1);           // 自定义标记点1
const marker2 = ref(-1);           // 自定义标记点2
const showInfoDialog = ref(false); // 时间信息弹窗显示状态

// 计算属性 - 时间格式化
const currentTimeFormatted = computed(() => formatTime(currentTime.value));
const durationFormatted = computed(() => formatTime(duration.value));
const startTimeFormatted = computed(() => formatTime(startTime.value));
const endTimeFormatted = computed(() => formatTime(endTime.value));

// 计算属性 - 时间差计算
const timeSpanFormatted = computed(() => {
  const span = endTime.value >= startTime.value ? endTime.value - startTime.value : 0;
  return formatTime(span);
});

/* const relativeToStartFormatted = computed(() => {
  const relative = currentTime.value >= startTime.value ? currentTime.value - startTime.value : 0;
  return formatTime(relative);
}); */
const marker1RelativeToStartFormatted = computed(() => {
  const start = startTime.value === -1 ? 0 : startTime.value;
  const relative = marker1.value >= start ? marker1.value - start : 0;
  return formatTime(relative);
});

const marker1Formatted = computed(() => formatTime(marker1.value));
const marker2Formatted = computed(() => formatTime(marker2.value));

const markersDistanceFormatted = computed(() => {
  if (marker1.value < 0 || marker2.value < 0 || marker2.value <= marker1.value) return '0.00';
  const distance = Math.abs(marker2.value - marker1.value);
  return formatTime(distance);
});

// 方法 - 时间格式化
function formatTime(seconds: number): string {
  if (seconds == -1) return '';
  return seconds.toFixed(2);
}

// 方法 - 视频错误处理
function handleVideoError() {
  if (!videoPlayer.value) return;

  const errorCode = videoPlayer.value.error?.code;

  if ([2, 4].includes(errorCode as number)) {
    ElMessage.error({
      message: '视频播放失败，请尝试更新cookie后重试',
      duration: 5000
    });
  } else {
    ElMessage.error(`视频播放失败 (错误码: ${errorCode})`);
  }

  console.error('视频播放错误:', videoPlayer.value.error);
}

// 方法 - 设置起点时间
function setStartTime() {
  if ((currentTime.value > marker1.value && marker1.value >= 0) || (currentTime.value > marker2.value && marker2.value >= 0)) {
    ElMessage.warning('起点时间不能大于标记点');
    return;
  }
  if (endTime.value >= 0 && currentTime.value > endTime.value) {
    ElMessage.warning('起点时间不能大于终点时间');
    return;
  }

  startTime.value = currentTime.value;
  //ElMessage.success(`已设置起点时间: ${startTimeFormatted.value}s`);
}

// 方法 - 设置终点时间
function setEndTime() {
  if ((currentTime.value < marker1.value && marker1.value >= 0) || (currentTime.value < marker2.value && marker2.value >= 0)) {
    ElMessage.warning('终点时间不能小于标记点');
    return;
  }
  if (startTime.value >= 0 && currentTime.value < startTime.value) {
    ElMessage.warning('终点时间不能小于起点时间');
    return;
  }
  endTime.value = currentTime.value;
  //ElMessage.success(`已设置终点时间: ${endTimeFormatted.value}s`);
}

// 方法 - 前进0.02秒
function stepForward() {
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = Math.min(
      videoPlayer.value.currentTime + 0.02,
      duration.value
    );
  }
}

// 方法 - 后退0.02秒
function stepBackward() {
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = Math.max(
      videoPlayer.value.currentTime - 0.02,
      0
    );
  }
}

// 方法 - 添加自定义标记点1
function addMarker1() {
  if (currentTime.value < startTime.value) {
    ElMessage.warning('标记点不能小于起点时间');
    return;
  }
  if (currentTime.value > endTime.value && endTime.value >= 0) {
    ElMessage.warning('标记点不能大于终点时间');
    return;
  }
  marker1.value = currentTime.value;
  //ElMessage.success(`已添加标记点1: ${marker1Formatted.value}s`);
}

// 方法 - 添加自定义标记点2
function addMarker2() {
  if (currentTime.value < startTime.value) {
    ElMessage.warning('标记点不能小于起点时间');
    return;
  }
  if (currentTime.value > endTime.value && endTime.value >= 0) {
    ElMessage.warning('标记点不能大于终点时间');
    return;
  }
  marker2.value = currentTime.value;
  //ElMessage.success(`已添加标记点2: ${marker2Formatted.value}s`);
}

// 新增方法 - 清除标记点1
function clearMarker1() {
  if (marker1.value >= 0) {
    marker1.value = -1;
    //ElMessage.success('已清除标记点1');
  }
}

// 新增方法 - 清除标记点2
function clearMarker2() {
  if (marker2.value >= 0) {
    marker2.value = -1;
    //ElMessage.success('已清除标记点2');
  }
}

// 方法 - 在标记点1添加attack
function addAttackAtMarker1() {
  if (marker1.value < 0) {
    ElMessage.warning('请先设置标记点1');
    return;
  }
  
  emit('add-attack', {
    beginTime: marker1RelativeToStartFormatted.value,
    delay: markersDistanceFormatted.value,
  });
  
  //ElMessage.success(`已在标记点1(${marker1Formatted.value}s)添加attack`);
}

// 新增方法 - 退出播放器
function exitPlayer() {
  // 清空所有状态
  if (videoPlayer.value) {
    videoPlayer.value.pause();
    videoPlayer.value.currentTime = 0;
  }
  
  currentTime.value = 0;
  startTime.value = -1;
  endTime.value = -1;
  marker1.value = -1;
  marker2.value = -1;
  showInfoDialog.value = false;
  
  // 抛出退出事件
  emit('exit');
  
  ElMessage.info('已退出视频播放');
}

// 方法 - 跳转到指定时间点
function jumpToTime(time: number) {
  if (videoPlayer.value && time > 0) {
    videoPlayer.value.currentTime = time;
    //ElMessage.info(`已跳转到: ${formatTime(time)}s`);
  }
}

// 方法 - 处理时间更新事件
function handleTimeUpdate() {
  if (videoPlayer.value) {
    currentTime.value = videoPlayer.value.currentTime;
  }
}

// 方法 - 处理视频元数据加载完成事件
function handleLoadedMetadata() {
  if (videoPlayer.value) {
    duration.value = videoPlayer.value.duration;
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 初始化逻辑
});
</script>

<style scoped>
.video-player-container {
  max-width: 1000px;
  margin: 10px 5px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.video-wrapper {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
  transition: box-shadow 0.3s ease;
}

.video-wrapper:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.video-player {
  width: 100%;
  display: block;
}

.basic-info-bar {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.info-item {
  margin-right: 30px;
  display: flex;
  align-items: center;
}

.info-label {
  color: #666;
  margin-right: 8px;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.control-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  margin-bottom: 20px;
}

.control-btn {
  transition: all 0.2s ease;
}

.control-btn:hover {
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
  filter: brightness(1.02);
}

.control-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
}

.markers-display {
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;
  padding: 12px;
  background-color: #f9fafb;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.marker-tag {
  transition: all 0.2s ease;
  cursor: pointer;
}

.marker-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-content {
  padding: 10px 0;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.dialog-label {
  width: 120px;
  color: #666;
  font-size: 14px;
}

.dialog-value {
  flex: 1;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .control-panel {
    flex-direction: column;
    align-items: flex-start;
  }

  .button-group {
    width: 100%;
    justify-content: center;
  }
  
  .basic-info-bar {
    flex-direction: column;
    gap: 8px;
  }
  
  .info-item {
    margin-right: 0;
  }
}
</style>


